package com.yonyou.cms.epc.service.shoppingCart.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cms.epc.client.dto.shoppingCart.ShoppingCartDTO;
import com.yonyou.cms.epc.client.entity.shoppingCart.ShoppingCartPO;
import com.yonyou.cms.epc.mapper.shoppingCart.ShoppingCartMapper;
import com.yonyou.cms.epc.service.shoppingCart.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 购物车service实现类
 * @author: chengbufang
 * @date: 2022-06-29 14:49
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCartPO> implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 查询购物车列表
     * @param params
     * @return
     */
    @Override
    public List<ShoppingCartPO> getCartList(Map<String, Object> params) {

        return shoppingCartMapper.getCartList(params);
    }

    /**
     * 购物车提交订单时构建数据
     * @param cartList
     * @return
     */
    @Override
    public List<Map<String, Object>> reportOrder(List<ShoppingCartPO> cartList) {

        Map<String, Object> params = new HashMap<>();
        params.put("partCodeList", cartList.stream().map(ShoppingCartPO::getPartCode).collect(Collectors.toList()));

        List<Map<String, Object>> orderList = shoppingCartMapper.reportOrder(params);
        // 取页面传的数量，计算金额
        for (Map<String, Object> order : orderList) {
            String partNo = order.get("partNo").toString();
            for (ShoppingCartPO cart : cartList) {
                String partCode = cart.getPartCode();
                if (partCode.equals(partNo)) {
                    // 订购数量
                    BigDecimal count = new BigDecimal(cart.getPartCount());
                    order.put("purchaseQuantity", count);
                    // 订购金额
                    BigDecimal price = new BigDecimal(order.get("purchasePrice").toString());
                    order.put("purchaseAmount", price.multiply(count));
                }
            }
        }
        return orderList;
    }

    /**
     * 加入购物车
     * @param shoppingCartDto
     */
    @Override
    public Map<String, Object> pushToCart(ShoppingCartDTO shoppingCartDto) {
        Map<String, Object> result = new HashMap<>();

        // 查询是否已存在
        LambdaQueryWrapper<ShoppingCartPO> wrapper = new QueryWrapper<ShoppingCartPO>().lambda();
        wrapper.eq(ShoppingCartPO::getPartCode, shoppingCartDto.getPartCode());
        wrapper.eq(ShoppingCartPO::getCreatedBy, shoppingCartDto.getCreatedBy());
        wrapper.eq(ShoppingCartPO::getOwnerCode, shoppingCartDto.getOwnerCode());
        Integer exit = shoppingCartMapper.selectCount(wrapper);
        if(exit > 0) {
            result.put("code", "1");
            result.put("message", "购物车中已存在");
            return result;
        }

        // 初始赋值添加
        ShoppingCartPO shoppingCartPo = shoppingCartDto.transDtoToPo(ShoppingCartPO.class);
        shoppingCartPo.setPartCount(0);
        shoppingCartPo.setUpdatedBy(shoppingCartPo.getCreatedBy());

        shoppingCartMapper.pushToCart(shoppingCartPo);
        result.put("code", "0");
        result.put("message", "加入购物车成功");
        return result;
    }

    /**
     * 删除购物车
     * @param ids
     * @return
     */
    @Override
    public Map<String, Object> deleteFromCart(List<Long> ids) {
        Map<String, Object> result = new HashMap<>();

        Integer res = shoppingCartMapper.deleteFromCart(ids);

        if (res > 0) {
            result.put("code", "0");
            result.put("message", "删除成功");
        } else {
            result.put("code", "1");
            result.put("message", "删除失败");
        }
        return result;
    }

    /**
     * 查询购物车条数
     * @param params
     * @return
     */
    @Override
    public Integer getCartCount(Map<String, Object> params) {
        LambdaQueryWrapper<ShoppingCartPO> wrapper = new QueryWrapper<ShoppingCartPO>().lambda();
        wrapper.eq(ShoppingCartPO::getCreatedBy, params.get("userId"));
        wrapper.eq(ShoppingCartPO::getOwnerCode, params.get("ownerCode"));

        return shoppingCartMapper.selectCount(wrapper);
    }

    /**
     * 清空购物车
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> clearCart(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        LambdaQueryWrapper<ShoppingCartPO> wrapper = new QueryWrapper<ShoppingCartPO>().lambda();
        wrapper.eq(ShoppingCartPO::getCreatedBy, params.get("userId"));
        wrapper.eq(ShoppingCartPO::getOwnerCode, params.get("ownerCode"));

        int rows = shoppingCartMapper.delete(wrapper);

        if (rows > 0) {
            result.put("code", "0");
            result.put("message", "清空购物车成功");
        } else {
            result.put("code", "1");
            result.put("message", "清空购物车失败");
        }
        return result;
    }

    /**
     * 校验备件是否符合订单类型
     * @param params
     * @return
     */
    @Override
    public Integer checkOrderType(Map<String, Object> params) {

        // 转换异常，需要先用JSON转一下
        String s = JSON.toJSONString(params.get("orderParts"));
        List<ShoppingCartPO> cartList = JSONObject.parseArray(s, ShoppingCartPO.class);

        params.put("idList", cartList.stream().map(ShoppingCartPO::getId).collect(Collectors.toList()));

        return shoppingCartMapper.checkOrderType(params);
    }
}
